package com.aisi.backend.service.impl;

import com.aisi.backend.domain.entity.Account;
import com.aisi.backend.domain.entity.AccountDetails;
import com.aisi.backend.domain.entity.Topic;
import com.aisi.backend.domain.vo.request.TopicCreateVo;
import com.aisi.backend.domain.vo.request.TopicUpdateVo;
import com.aisi.backend.domain.vo.response.TopicDetailVo;
import com.aisi.backend.domain.vo.response.TopicPreviewVo;
import com.aisi.backend.mapper.AccountDetailsMapper;
import com.aisi.backend.mapper.AccountMapper;
import com.aisi.backend.mapper.TopicMapper;
import com.aisi.backend.service.TopicService;
import com.aisi.backend.utils.MybatisUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.apache.ibatis.session.SqlSession;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @Author: shenjianZ
 * @Date: 2024/5/11 下午9:19
 * @Description:
 */


public class TopicServiceImpl implements TopicService {

    @Override
    public boolean createTopic(Integer userId, TopicCreateVo topicCreateVo) {
        try (SqlSession session = MybatisUtil.getSqlSession(true)) {
            TopicMapper mapper = session.getMapper(TopicMapper.class);
            Topic topic = new Topic();
            topic.setTitle(topicCreateVo.getTitle());
            topic.setContent(topicCreateVo.getContent().toJSONString());
            topic.setType(topicCreateVo.getType());
            topic.setUid(userId);
            topic.setTime(new Date());
            Integer i = mapper.addTopic(topic);
            return i > 0;
        }
    }

    @Override
    public List<TopicPreviewVo> listTopic(Integer page, Integer type) {
        List<Topic> topics;
        try (SqlSession session = MybatisUtil.getSqlSession(true)) {
            TopicMapper mapper = session.getMapper(TopicMapper.class);
            // 查询所有主题
            if (type == 0) topics = mapper.listTopicAll(page*20);
            // 查询指定类型主题
            else topics = mapper.listTopic(page*20 ,type);
        }
        if (topics.isEmpty()) return null;
        return topics.stream().map(this::resolveToPreviewVo).toList();
    }

    @Override
    public TopicDetailVo listTopicDetail(Integer tid) {
        try (SqlSession session = MybatisUtil.getSqlSession(true)) {
            TopicDetailVo vo = new TopicDetailVo();
            TopicMapper topicMapper = session.getMapper(TopicMapper.class);
            Topic topic = topicMapper.findTopicById(tid);
            vo.setTitle(topic.getTitle());
            vo.setId(topic.getId());
            vo.setType(topic.getType());
            vo.setTime(topic.getTime());
            vo.setContent(topic.getContent());
            TopicDetailVo.User user = new TopicDetailVo.User();
            AccountMapper accountMapper = session.getMapper(AccountMapper.class);
            Account account = accountMapper.findAccountById(topic.getUid());
            user.setUsername(account.getUsername());
            user.setAvatar(account.getAvatar());
            user.setEmail(account.getEmail());
            AccountDetailsMapper detailsMapper = session.getMapper(AccountDetailsMapper.class);
            AccountDetails accountDetails = detailsMapper.findAccountDetailsById(topic.getUid());
            user.setQq(accountDetails.getQq());
            user.setWx(accountDetails.getWx());
            user.setPhone(accountDetails.getPhone());
            user.setId(topic.getUid());
            user.setDescription(accountDetails.getDescription());
            user.setSex(accountDetails.getSex());
            vo.setUser(user);
            return vo;
        }

    }

    @Override
    public Integer updateTopic(Integer userId, TopicUpdateVo topicUpdateVo) {
        try (SqlSession session = MybatisUtil.getSqlSession(true)) {
            TopicMapper mapper = session.getMapper(TopicMapper.class);
            Topic topic = new Topic();
            topic.setId(topicUpdateVo.getId());
            topic.setTitle(topicUpdateVo.getTitle());
            topic.setContent(topicUpdateVo.getContent().toJSONString());
            topic.setType(topicUpdateVo.getType());
            return mapper.updateTopic(topic, userId);
        }
    }

    public TopicPreviewVo resolveToPreviewVo (Topic topic){
            TopicPreviewVo previewVo = new TopicPreviewVo();
            previewVo.setId(topic.getId());
            previewVo.setTitle(topic.getTitle());
            previewVo.setType(topic.getType());
            previewVo.setTime(topic.getTime());
            previewVo.setUid(topic.getUid());
            previewVo.setAvatar(topic.getAvatar());
            previewVo.setUsername(topic.getUsername());
            StringBuilder previewText = new StringBuilder();
            JSONArray ops = JSONObject.parse(topic.getContent()).getJSONArray("ops");
            for (Object op : ops) {
                if (op instanceof JSONObject operation) {
                    Object insert = operation.get("insert");
                    if (insert instanceof String text) {
                        if (previewText.length() > 300) {
                            continue;
                        }
                        previewText.append(text);
                    }
                }
            }
            previewVo.setText(previewText.length() > 300 ? previewText.substring(0, 300) : previewText.toString());
            return previewVo;
        }

    }
